package BookManagement.controller;

import BookManagement.domain.User;
import BookManagement.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    //跳转登录界面
    @RequestMapping ("/toLogin")
    public ModelAndView toLogin(){
        ModelAndView mav=new ModelAndView("account/indexLogin");
        return mav;
    }

    //登录
    @RequestMapping ("/login")
    public ModelAndView login(String username, String password, HttpSession hs){
        ModelAndView mav=new ModelAndView();
        User user = userService.findUserByUsername(username);
        if(user==null){
            mav.setViewName("account/loginFail");
            return mav;
        }
        else if(!user.getPassword().equals(password)){
            mav.setViewName("account/loginFail");
            return mav;
        }
        else{
            if(user.getIdentity().equals("admin")){
                hs.setAttribute("usercurrent",user.getUserName());
                hs.setAttribute("validated","admin");
                mav.addObject("logininfo","管理员登录");
                mav.setViewName("admin/indexAdmin");
                return mav;
            }else{
                hs.setAttribute("usercurrent",user.getUserName());
                hs.setAttribute("validated","user");
                hs.setAttribute("balance",user.getBalance());
                hs.setAttribute("indexname",user.getName());
                hs.setAttribute("sex",user.getSex());
                mav.addObject("logininfo","用户登录");
                mav.setViewName("redirect:/user/index");
                return mav;
            }
        }
    }

    //用户注册
    @RequestMapping("/register")
    public ModelAndView register(String username, String password, String name, String sex, String birth, String signature, HttpSession hs){
        ModelAndView mav=new ModelAndView();
        if(userService.findUserByUsername(username)!=null){
            mav.setViewName("account/registerFail");
            return mav;
        }
        String photoAddr=new String();
        User u=new User(name,sex,birth,photoAddr,signature,0,"D",0,0,0);
        u.setUserName(username);
        u.setPassword(password);
        u.setIdentity("user");
        userService.addUser(u);
        mav.addObject("registerinfo","注册成功");
        mav.setViewName("account/registerSuccess");
        return mav;
    }

    //跳转修改帐户界面
    @RequestMapping("/toUpdateAccount")
    public ModelAndView toUpdate(HttpSession hs){
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        hs.setAttribute("sex",user.getSex());
        mav.setViewName("/user/updateAccount");
        mav.addObject("user",user);
        return mav;
    }
    //修改帐户信息
    @RequestMapping("/updateAccount")
    public ModelAndView update(String username,String name, String sex, String birth, @RequestParam("photo") CommonsMultipartFile file, String signature, HttpSession hs) throws IOException {
        ModelAndView mav=new ModelAndView();
        User user=userService.findUserByUsername(username);
        String photo=null;
        if(user.getPhoto().equals("")&&!file.isEmpty()){
            String path=hs.getServletContext().getRealPath("/userImages/");
            String fileName=file.getOriginalFilename();
            String filetype=fileName.substring(fileName.lastIndexOf("."));
            File target=new File(path,username+filetype);
            photo="/userImages/"+username+filetype;
            try{
                file.getFileItem().write(target);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(!file.isEmpty()){
            Files.delete(Paths.get(hs.getServletContext().getRealPath(user.getPhoto())));
            String path=hs.getServletContext().getRealPath("/userImages/");
            String fileName=file.getOriginalFilename();
            String filetype=fileName.substring(fileName.lastIndexOf("."));
            File target=new File(path,username+filetype);
            photo="/userImages/"+username+filetype;
            try{
                file.getFileItem().write(target);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        user.setName(name);user.setSex(sex);user.setBirth(birth);user.setSignature(signature);
        if(photo!=null)user.setPhoto(photo);
        int i=userService.updateUser(user);
        if(i>0){
            hs.setAttribute("indexname",user.getName());
            mav.setViewName("account/updateSuccess");
            mav.addObject("updateMsg","更新成功");
            return mav;
        }else{
            mav.setViewName("account/updateFail");
            mav.addObject("updateMsg","更新失败");
            return mav;
        }
    }

    //跳转修改密码界面
    @RequestMapping("/toUpdatePassword")
    public ModelAndView toUpdatePassword(HttpSession hs){
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        ModelAndView mav=new ModelAndView();
        mav.addObject("oldPassword",user.getPassword());
        mav.setViewName("/user/pwdModify");
        return mav;
    }

    //修改密码
    @RequestMapping("/updatePassword")
    public ModelAndView updatePassword(@RequestParam("newPassword") String password,HttpSession hs){
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        user.setPassword(password);
        userService.updateUser(user);
        return new ModelAndView("redirect:/user/index");
    }

    //显示对错图片
    @RequestMapping("/readChangePhoto")
    public void readChangePhoto(String str, HttpServletResponse response,HttpSession hs) {
        try {
            FileInputStream fis=new FileInputStream(hs.getServletContext().getRealPath("/statics/images/"+str+".png"));
            int available = fis.available();
            byte[] date = new byte[available];
            fis.read(date);
            fis.close();
            //这里要有这个设置，否则会报错
            response.setContentType("img/*");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream out = response.getOutputStream();
            out.write(date);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
